package scau.mis4.chanyulin.tools.utils;

import java.io.*;

/**
 * Created by cyl on 2017/3/30
 * 文件操作工具类
 */
public class FileUtils {

    /**
     * 获取文件后缀
     * @param fileName 文件名
     */
    public static String getFileExtensions(String fileName) {
        if (fileName.contains("."))
            return fileName.substring(fileName.lastIndexOf("."));
        else
            return null;
    }

    /**
     * 获取文件夹名
     * @param path 文件夹路径
     */
    public static String getFolderName(String path) {
        if (path.contains("\\")) {
            if (path.endsWith("\\")) {
                return getFolderName(path.substring(0, path.length() - 1));
            } else
                return path.substring(path.lastIndexOf("\\") + 1);
        } else
            return null;
    }

    /**
     * 根据路径判断文件或文件夹是否存在
     * @param path 文件或文件夹路径
     */
    public static boolean isFileExists(String path) {
        return new File(path).exists();
    }

    /**
     * 读取文件内容为字符串
     * @param path 文件路径
     */
    public static String readFile(String path) throws IOException {
        StringBuilder result = new StringBuilder();
        FileReader reader;
        reader = new FileReader(new File(path));
        BufferedReader br = new BufferedReader(reader);
        String temp;
        while((temp = br.readLine()) != null) {
            result.append(temp).append(System.lineSeparator());
        }
        reader.close();
        br.close();
        return result.toString();
    }

    /**
     * 将字符串写入文件
     * @param text 文件内容
     * @param path 文件路径
     */
    public static void writeFile(String text, String path) throws IOException {
        File file = new File(path);
        FileWriter writer;
        writer = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(writer);
        bw.write(text);
        bw.flush();
        writer.close();
        bw.close();
    }

}
